<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.code" placeholder="版本号或描述" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="版本号" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Version }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.FileSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述信息" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Descritpion }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.Dt }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="版本号" prop="Version">
          <el-input v-model="temp.Version" />
        </el-form-item>

        <el-form-item label="描述" prop="Description">
          <el-input v-model="temp.Description" />
        </el-form-item>

        <el-form-item label="升级包" prop="升级包">
          <el-upload
            class="upload-demo"
            action=""
            :file-list="filelist"
            :before-upload="handleBeforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createData()">
          保存
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import * as homeHttp from '@/api/home'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        code: undefined
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        Version: undefined,
        id: undefined,
        Description: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '上传升级包'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      filelist: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      const res = await homeHttp.getPackages(this.listQuery)

      if (res.data.Result) {
        this.list = res.data.Data
        this.total = res.data.Total
      }

      this.listLoading = false
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        Version: undefined,
        Description: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          homeHttp.AddApp(this.temp).then(res => {
            if (res.data.Result) {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },

    handleBeforeUpload(file) {
      const reader = new FileReader()

      reader.readAsDataURL(file)
      reader.onload = (e) => {
        // base64 数据流
        this.temp.Base64Content = e.target.result
        this.temp.FileName = file.name

        let size = file.size

        if (size < 0.01 * 1024) {
          // 小于 0.1k 转化单位 B
          size = size.toFixed(2) + 'B'
        } else if (size < 0.01 * 1024 * 1024) {
          // 如果小于0.1MB转化成KB
          size = (size / 1024).toFixed(2) + 'KB'
        } else if (size < 0.01 * 1024 * 1024 * 1024) {
          // 如果小于0.1GB转化成MB
          size = (size / 1024 / 1024).toFixed(2) + 'MB'
        } else {
          size = (size / 1024 / 1024 / 1024).toFixed(2) + 'GB'
        }

        this.temp.size = size

        return size
      }
      this.filelist = [file]

      return false
    }
  }
}
</script>
